package com.test.platform.module.perf.service;

import com.test.common.component.RedisComponent;
import com.test.common.entity.perf.PerfAgentCacheInfo;
import com.test.common.entity.perf.PerfAgentEntity;
import com.test.common.entity.perf.PerfReportEntity;
import com.test.common.repository.perf.PerfAgentRepository;
import com.test.common.response.BizException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Optional;

@Slf4j
@Service
public class PerfAgentService {

    @Resource
    private RedisComponent redisComponent;

    @Resource
    private PerfAgentRepository perfAgentRepository;

    public Object searchAll(int pageNo, int pageSize) {
        Page<PerfAgentEntity> resPage = perfAgentRepository.findAll(PageRequest.of(pageNo - 1, pageSize, new Sort(Sort.Direction.DESC, "id")));
        for (PerfAgentEntity agentEntity : resPage.getContent()) {
            PerfAgentCacheInfo agentCacheInfo = redisComponent.get("perf:agent:" + agentEntity.getId(), PerfAgentCacheInfo.class);
            if (agentCacheInfo != null) {
                agentEntity.setPerfAgentCacheInfo(agentCacheInfo);
            }
        }
        if (resPage.getSize() > 0) {
            return resPage;
        } else {
            throw new BizException("没有查询到任何数据");
        }
    }

    // 执行机信息只放Redis
    public Object reflush(PerfAgentEntity perfAgentEntity) {

        Optional<PerfAgentEntity> entityOptional = perfAgentRepository.findByUrl(perfAgentEntity.getUrl());
        if (entityOptional.isPresent()) {
            // 已注册，更新
            redisComponent.set("perf:agent:" + entityOptional.get().getId(), perfAgentEntity.getPerfAgentCacheInfo(), 15);
        } else {
            // 未注册，新增
            PerfAgentEntity saved = perfAgentRepository.save(perfAgentEntity);
            redisComponent.set("perf:agent:" + saved.getId(), perfAgentEntity.getPerfAgentCacheInfo(), 15);
        }

        return "成功";
    }
}
